package wena

import (
	"context"
	"io"
	"log"
	"path/filepath"

	"gitee.com/go-wena/env"
	"gitee.com/go-wena/proc"
	"gitee.com/go-wena/wena/internal/dep"
	"gitee.com/go-wena/wena/utils/httpx"
	"github.com/adrg/xdg"
)

var goRoot = filepath.Join(xdg.DataHome, "wena", "go")

func init() {
	env.SetEnv("PATH", filepath.Join(goRoot, "bin")+string(filepath.ListSeparator)+env.GetString("PATH"))
}

func GoExist(ctx context.Context) error {
	return proc.Command(filepath.Join(goRoot, "bin", "go"), "version").Context(ctx).Start()
}

func GoDownload(ctx context.Context, force bool, progress httpx.ProgressFunc) error {
	if !force {
		if err := GoExist(ctx); err != nil {
			log.Printf("%v", err)
		} else {
			return nil
		}
	}
	log.Printf("goRoot: %s\n", goRoot)
	return dep.DownloadNewestGo(ctx, goRoot, progress)
}

func PrintGoVersion(ctx context.Context, w io.Writer) error {
	return proc.Command("go", "version").Context(ctx).StdOut(w).ErrOut(w).Start()
}

func PrintGoEnv(ctx context.Context, w io.Writer) error {
	return proc.Command("go", "env").Context(ctx).StdOut(w).ErrOut(w).Start()
}
